package com.zrrd.yt.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yt.model.product.BaseAttrInfo;
import com.zrrd.yt.model.product.BaseAttrValue;
import com.zrrd.yt.product.mapper.BaseAttrInfoMapper;
import com.zrrd.yt.product.mapper.BaseAttrValueMapper;
import com.zrrd.yt.product.service.BaseAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BaseAttrServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrService {

   @Autowired
   private BaseAttrInfoMapper baseAttrInfoMapper;
   @Autowired
   private BaseAttrValueMapper baseAttrValueMapper;

    @Override
    public List<BaseAttrInfo> selectBaseAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    @Transactional
    public void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {
        //判断是修改还是添加
        if(baseAttrInfo.getId() != null){
            this.updateById(baseAttrInfo);
        }else{
            //保存平台属性信息
            this.save(baseAttrInfo);
        }
        //根据属性id作为条件 删除属性值表的对应数据
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(wrapper);

        //获取传递过来的属性值集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if(attrValueList !=null && attrValueList.size() > 0 ){
            //遍历集合
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //给每个属性值 设置属性id
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                //添加属性值
                baseAttrValueMapper.insert(baseAttrValue);
            }

        }
    }

    @Override
    public List<BaseAttrValue> getAttrInfo(Long attrId) {
        //根据属性ID获取属性值的集合
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id",attrId);
        List<BaseAttrValue> valueList = baseAttrValueMapper.selectList(wrapper);
        //返回属性对象
        return valueList;
    }

    @Override
    public List<BaseAttrInfo> selectBaseAttrInfoListBySkuId(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }
}
